package com.scalar.chiptrack.adaptor.ispl;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;
import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FTPConnectMode;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * User: ChandraSekhar
 * Date: Sep 7, 2007
 * Time: 1:04:13 PM
 */
public class ISPLFTPAdaptor extends JobHandler implements AdaptorConstants
{

    private static final int    PORT            = 21;
    private static final String FTP_HOST        = "121.97.86.131"; //spectra@ftp.isplphil.com
    public  static final String ADAPTOR_TYPE    = "ISPL_TEST";
    public  static final String FILE_NAME_WIP   = "Spectralinear test Wip";
    private static final String FILE_EXTN_XLS  = ".XLS";
    private static final String HOME_DIR        = "/Spectra/WIP/";

    private String m_username           = null;
    private String m_password           = null;
    private Logger m_adaptorLogger      = null;
    private String m_dataOutputDir      = null;


    public ISPLFTPAdaptor() throws Exception
    {
        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation(VENDOR_NAME_ISPL, WIP_TYPE_TEST );

            m_username = vendorAdaptor.getUserId();
            m_password = vendorAdaptor.getPassWord();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory();

            if (m_dataOutputDir != null)
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
            }

            AdaptorUtils.makeAllAdaptorDirs(m_dataOutputDir);
            m_adaptorLogger = AdaptorUtils.getAdaptorLogger(m_dataOutputDir, VENDOR_NAME_ISPL);

        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading ISPL Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }

    }

    public static void main( String[] args ) throws Exception
    {
        new ISPLFTPAdaptor().execute();
    }

    public void execute() throws Exception
    {
        try
        {
            printHeader();

            removeOldFiles();

            FTPClient ftp = login( FTP_HOST, PORT, m_username, m_password );
            log( "Successfully logged in to " + FTP_HOST );
            System.out.println( "Successfully logged in to " + FTP_HOST );

            // change the directory to data
            ftp.chdir(HOME_DIR);
            log("Remote directory changed to " + HOME_DIR);
            System.out.println("Remote directory changed to " + HOME_DIR);

            //To Down DownLoad the File To Local System at Specepied path
            downloadWIPFiles( ftp );

            // Log out
            logout( ftp );
            log( "\nSuccessfully logged out from ISPL Ftp Site" );
            System.out.println( "\nSuccessfully logged out from ISPL FTP Site" );
        }
        catch ( Exception e )
        {
            throw e;
        }
    }
    /**
     *
     * @param host
     * @param port
     * @param m_username
     * @param m_password
     * @return
     * @throws Exception
     */
    private FTPClient login( String host, int port, String m_username, String m_password ) throws Exception
    {
        FTPClient ftp = new FTPClient( host, port );
        ftp.login( m_username, m_password );
        ftp.debugResponses( false );
        ftp.setType( FTPTransferType.BINARY );
        // active does not allows me connect to ftp site even any proxy lies in path.
        ftp.setConnectMode( FTPConnectMode.PASV );
        return ftp;
    }

    private void downloadWIPFiles( FTPClient ftp ) throws Exception
    {
        String[] listings = ftp.dir();

        if ( ( listings == null ) || ( listings.length == 0 ) )
        {
            return;
        }

        byte[] buf                          = null;
        FileOutputStream fileOutputStream   = null;
        String         tempFileName         = null;
        try
        {

            System.out.println( "\tDownloading Test Wip Standard files...." );

            // Downloading all the vendor files whose date greater than or equal to the last Adaptor Run Time.
            for ( int i = 0; i < listings.length; i++ )
            {
                if ( listings[i].startsWith( FILE_NAME_WIP ) )
                {
                    if ( tempFileName == null )
                    {
                        tempFileName = listings[i];
                    }
                   else
                   {
                        java.util.Date date1 = ftp.modtime( tempFileName );
                        java.util.Date date2 = ftp.modtime( listings[i] );
                        if ( date2.compareTo( date1 ) > 0 )
                        {
                            tempFileName = listings[i];
                        }
                    }
                }
            }
            if (   tempFileName != null )
            {
                log( "\ndownloading file " + tempFileName + " to " + m_dataOutputDir + " directory... " );
                java.util.Date uploadDate = ftp.modtime( tempFileName );
                buf = ftp.get( tempFileName );
                int tempLength = tempFileName.lastIndexOf('.');
                tempFileName = tempFileName.substring( 0, tempLength);
                tempFileName = tempFileName  +"-"+ StringUtils.formatDateToString( uploadDate, "MM-dd-yyyy-HH-mm-ss") + "_" + AdaptorUtils.getTimeAsString() + FILE_EXTN_XLS;
                fileOutputStream = new FileOutputStream( m_dataOutputDir + "/" + tempFileName, false );
                fileOutputStream.write( buf );
                fileOutputStream.flush();
            }
        }
        catch ( Exception e )
        {
            log( "Exception while downloading......... " + e );
            throw e;
        }
        finally
        {
            if ( fileOutputStream != null )
            {
                try
                {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                catch ( IOException ignore )
                {
                    System.out.println("ignore = " + ignore);
                }
            }
        }
    }
    /**
     *
     * @param ftp
     * @throws Exception
     */
    private void logout( FTPClient ftp ) throws Exception
    {
        if ( ftp == null )
        {
            return;
        }
        try
        {
            ftp.quit();
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From ISPL Extract FTP Site" + ignore );
            throw ignore;
        }
        ftp = null;
    }

    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }

    private void removeOldFiles() throws Exception
    {
        try
        {
            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );
        }
        catch (ScalarException se)
        {
            log( "Exception occurred while deleting old files at Adaptor Directory" );
            throw se;
        }
    }

    private void printHeader()
    {

        String message = "\n\n+----------- Running ISPL FTP Adaptor on " + new java.util.Date( System.currentTimeMillis() ) + " -------------+\n" +
                "\n+---------------------------------------------------------------+\n" +
                "+                                                                \n" +
                "+                        ISPL FTP Adaptor - Beta                 \n" +
                "+                                                                \n" +
                "+    Copy Right (C) 2007 - ScalarSoft Inc., All rights reserved.  \n" +
                "+                                                                \n" +
                "+---------------------------------------------------------------+\n";
        System.out.println( message );
        log( message );
    }
}
